package org.example.novel.utlis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工具包
 */
public class BeanHelper {

    private static Logger logger = LoggerFactory.getLogger(BeanHelper.class);

    public static <T> T copyProperties(Object o, Class<T> tClass) {

        try {

            if (o == null) return null;

            T t = tClass.newInstance();

            BeanUtils.copyProperties(o, t);

            return t;
        } catch (Exception e) {
            logger.error("对象类型数据转换异常:{}", e.getMessage());
            throw new RuntimeException("数据转换异常");
        }

    }

    public static <T> List<T> copyWithCollection(List<?> list, Class<T> tClass) {

        try {

            if (CollectionUtils.isEmpty(list)) return null;

            return list.stream().map(e -> copyProperties(e, tClass)).collect(Collectors.toList());
        } catch (Exception e) {
            logger.error("集合类型数据转换异常:{}", e.getMessage());
            throw new RuntimeException("数据转换异常");
        }
    }

    public static String toJsonStr(Object o) {
        try {
            return new ObjectMapper().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObj(String s, Class<T> tClass) {
        try {
            return new ObjectMapper().readValue(s, tClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
